package com.yqg.protection.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yqg.protection.common.Result;
import com.yqg.protection.entity.Menu;
import com.yqg.protection.service.IMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * MenuController 前端控制器
 *
 * @author suzhuang
 * @since 2023-07-05
 */
@RestController
@RequestMapping("/menu")
@Api(tags = "菜单管理")
public class MenuController {

    @Resource
    private IMenuService menuService;

    /**
     * 新增或者更新
     */
    @PostMapping("/edit")
    @ApiOperation("新增或更新菜单")
    public Result save(@RequestBody Menu menu) {
        return Result.success(menuService.saveOrUpdate(menu));
    }

    /**
     * 删除
     */
    @GetMapping("delete/{id}")
    @ApiOperation("根据ID删除菜单")
    public Result delete(@PathVariable Integer id) {
        Menu menu = menuService.getById(id);
        return Result.success(menuService.saveOrUpdate(menu));
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    @ApiOperation("查询所有菜单")
    public Result buildMenuTree() {
        List<Menu> list = menuService.list();
        List<Menu> treeMenu =
                list.stream()
                        .filter(i -> i.getPid() == null)
                        .map(i -> {
                            i.setMenuDtos(getChildren(i, list));
                            return i;
                        })
                        .collect(Collectors.toList());
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(treeMenu);
            System.out.println(json);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return Result.success(treeMenu);
    }

    private static List<Menu> getChildren(Menu node, List<Menu> list) {
        return list.stream()
                //当 参数的节点 == 循环的父节点（说明参数的节点 找到儿子了）
                .filter(i -> node.getId().equals(i.getPid()))
                //再次递归设置调用
                .map(i -> {
                    i.setMenuDtos(getChildren(i, list));
                    return i;
                })
                .collect(Collectors.toList());
    }

    /**
     * 查询所有父菜单
     */
    @GetMapping("/allPid")
    @ApiOperation("查询所有父菜单")
    public Result findAllPid() {
        List<Menu> allPid = menuService.findAllPid();
        Map<Integer, String> menuMap = new HashMap<>();
        for (int i = 0; i < allPid.size(); i++) {
            menuMap.put(allPid.get(i).getId(), allPid.get(i).getMenuName());
        }
        return Result.success(menuMap);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询菜单")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(menuService.getById(id));
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @ApiOperation("分页查询菜单")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Menu> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(menuService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}

